'use strict';

import { platform_userModel } from "../model/platform_user";
import { ServiceBase, Exceptions } from '../kalend';
import { menuService } from "./menu";
import { merchantService } from "./merchant";
import _ = require("underscore");
import { invitationService } from "./invitation";
import { common } from "../middleware/common";
import { roleService } from "./role";

class Platform_userService extends ServiceBase {
    constructor() {
        super(platform_userModel)
    }
    /** 后台登录方法 */
    async login(phone: any, password: any) {
        let data = await this.querySingle({
            phone: phone,
            password: password
        },
            {
                populateOptions: {
                    path: 'roleId',
                    select: ''
                },
                select: 'name roleId merchantid status'
            }
        );
        if (data) {
            if (data.status === 0) {
                throw Exceptions.known("账号已禁用，请联系管理员");
            }
            if (data.roleId && data.roleId.length > 0) {
                data.roleName = (data.roleId as Array<any>).map((r) => {
                    return r.name;
                });
                let menus: Array<any> = [];
                (data.roleId as Array<any>).forEach((role: any) => {
                    if (role.rights && role.rights.length > 0) {
                        role.rights.map((right: any) => {
                            if (right)
                                menus.push({ menu: right.toJSON() });
                        })
                    }
                });
                if (menus.length > 0) {
                    data.menus = await menuService.getUserMenuTreeByRights(menus);
                } else {
                    throw Exceptions.known("联系管理员设置权限后方可登录");
                }
            } else {
                throw Exceptions.known("联系管理员设置权限后方可登录");
            }
        } else {
            throw Exceptions.known('手机号或密码错误');
        }
        delete data.roleId;
        return data;
    }
    async query(params: any) {
        const offset = params.offset;
        const limit = params.limit;
        const status = params.status;
        const name = params.name;
        const role = params.role;
        const areas = params.areas;
        const filter: any = {};
        if (name) {
            filter.name = { '$regex': name, $options: 'i' };
        }
        if (status === 0 || status === 1) {
            filter.status = status;
        }
        if (role) {
            filter.roleId = { $in: [role] };
        }
        if (areas && areas.length == 1) {
            filter.province = areas[0];
        }
        if (areas && areas.length == 2) {
            filter.province = areas[0];
            filter.city = areas[1];
        }
        if (areas && areas.length == 3) {
            filter.province = areas[0];
            filter.city = areas[1];
            filter.district = areas[2];
        }
        let result = await super.queryPagination(offset, limit, {
            filter: filter,
            select: 'name  phone roleId updateTime status customerid province city district balance',
            populateOptions: [{
                path: 'roleId',
                select: 'name'
            }],
            sort: { updateTime: -1 }
        });

        for (let index = 0; index < result.rows.length; index++) {
            const item = result.rows[index];
            if (item.status == '0') {
                item.status = '禁用';
            } else if (item.status == '1') {
                item.status = '有效';
            }
            item.rolename = item.roleId.map((a: any) => {
                return a.name;
            }).join(',')
            delete item.roleId;
            // 查询关联商户数量
            item.mernum = await merchantService.count({ agent: item._id });
            // 查询邀请记录
            if (item.customerid) {
                item.cusnum = await invitationService.queryCount(item.customerid);
            } else {
                item.cusnum = 0;
            }

            if (item.province) {
                item.area = item.province;
            }
            if (item.city) {
                item.area += ' ' + item.city;
            }
            if (item.district) {
                item.area += ' ' + item.district;
            }
        }
        // result.rows = result.rows.map((item) => {

        //     // if (item.phone) {
        //     //     item.phone = item.phone.substring(0, 3) + '****' + item.phone.substring(7, item.phone.length);
        //     // }
        //     if (item.status == '0') {
        //         item.status = '禁用';
        //     } else if (item.status == '1') {
        //         item.status = '有效';
        //     }
        //     item.rolename = item.roleId.map((a: any) => {
        //         return a.name;
        //     }).join(',')
        //     delete item.roleId;
        //     // 查询关联商户数量

        //     // 查询邀请记录

        //     return item;
        // });
        return result;
    }
    async lock(userid: any) {
        return this.update(userid, { status: 0 });
    }
    async open(userid: any) {
        return this.update(userid, { status: 1 });
    }
    async getuser(doc: any) {
        let type = doc.type;
        let mid = doc.mid;
        let data: Array<any> = [];
        // 关联餐厅账户
        if (type == 'ct') {
            let role = await roleService.querySingle({ name: { $regex: '餐厅', $options: 'i' } });
            data = await this.queryAll({
                filter: { status: 1, roleId: { $in: [role._id] }, $or: [{ merchantid: { $exists: false } }, { merchantid: mid }] },
                select: 'name phone'
            });
        } else if (type == 'ds') {// 关联大使账户
            let role = (await roleService.queryalls({ name: { $regex: '品牌宣传', $options: 'i' } })).map((a)=>{
                return a._id;
            });
            data = await this.queryAll({
                filter: { status: 1, roleId: { $in: role } },
                select: 'name phone'
            });
        }
        return data.map((a) => {
            a.name = `${a.name}<${a.phone}>`;
            delete a.phone;
            return a;
        });
    }

    async getSingleUser(params: any) {
        let user: any = await this.queryAll({ filter: { _id: params.userid } });
        for (let index = 0; index < user.length; index++) {
            const item = user[index]
            // 查询关联商户数量
            item.mernum = await merchantService.count({ agent: item._id });
            // 查询邀请记录
            item.cusnum = await invitationService.queryCount(item.customerid);
        }
        return user;
    }

    async updatepwd(params: any) {
        if (params.newpwd) {
            return this.update(params._id, { password: params.newpwd })
        }
    }
    //更新品牌大使余额
    async updateAgentBalance(doc: any) {
        let oneuser = await this.queryById(doc.agent);
        if (oneuser) {
            let addf = common.add(oneuser.balance || 0, doc.addm);
            this.update(doc.agent, { balance: addf });
            console.log('买单：所属品牌大使增加奖励' + doc.addm+'---成功');
        }
    }

    async queryMenuById(id: any) {
        let res: Array<any> = [];
        let data = await this.querySingle({
            _id: id
        },
            {
                populateOptions: {
                    path: 'roleId',
                    select: '',
                    populate: {
                        path: 'rights',
                        select: 'url'
                    }
                },
                select: 'name roleId'
            }
        );
        if (data) {
            if (data.roleId && data.roleId.length > 0) {
                data.roleId.forEach((role: any) => {
                    res = _.union(res, role.rights);
                });
            }
        }
        return res;
    }

    async editPass(doc: any) {
        let user = await this.querySingle({ _id: doc.uid, password: doc.password });
        if (!user) {
            throw Exceptions.known('原始密码输入错误');
        }
        if (doc.newpass !== doc.newpass2) {
            throw Exceptions.known('两次输入密码不一致，请核实');
        }
        if (doc.newpass == user.password) {
            throw Exceptions.known('新密码与旧密码一致，请核实');
        }
        return this.update(doc.uid, { password: doc.newpass });
    }

    async getviters(userid: any) {
        let result: Array<any> = [];
        let data = await this.queryById(userid);
        if (data.customerid) {
            result.push(data.customerid);
        }

        let mers = await merchantService.queryAlls({ agent: userid });
        let les: Array<any> = [];
        mers.forEach((item) => {
            if (item.legaluserid) {
                les.push(item.legaluserid);
            }
        });
        if (les.length > 0) {
            let users = await this.queryAll({ filter: { _id: { $in: les } }, select: 'customerid' });
            users.forEach((a) => {
                if (a.customerid) {
                    result.push(a.customerid);
                }
            })
        }

        return result;
    }
}

export const platform_userService = new Platform_userService();